import {
	showLoading,
	hideLoading
} from "./toast";
import {
	queryUploadSignature,
	uploadImage
} from '@/api/upload';
import {
	useStore
} from '@/store/index';
import {
	img_type
} from '@/constants/images.js';
import {
	showModal
} from "./toast";

/**
 * 获取oss配置
 * @param {String} 类型（如代理、商户）
 */
export function getOsssSignature(moduleType) {
	return new Promise((resolve, reject) => {
		queryUploadSignature({
			params: {
				// _action: 'signature',
				dir: `jzg/agent`
			}
		}).then(res => {
			console.log('获取文件上传签名==>', res);
			resolve(res.payload);
		});
	});
}

export function upload(imgFile) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: 'https://pos.bestyxb.com/agent-api/aliyun/uploadImage', //附件上传的服务器接口地址，非真实的接口地址
			filePath: imgFile, //要上传文件资源的路径,不同的组件
			name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容,即附件信息的接收字段名称
			formData: { //HTTP 请求中其他额外的 form data	
				'user': 'test'
			},
			success: (res) => { //回调方法
				if (res.data) {
					let reJson = JSON.parse(res.data);
					if (reJson && reJson.data && reJson.data
						.length > 0) {
						resolve(reJson.data[0].url);

					}
				}
			},
			fail: (res) => {
				console.log('res: ', res);
				uni.showModal({
					title: "提示",
					content: "上传失败，请检查网络" +
						JSON.stringify(res),
					success: function(res) {
						if (res.confirm) {
							console.log(
								"用户点击确定");
							upload();
						} else if (res.cancel) {
							console.log(
								"用户点击取消");
						}
					},
				});
			},
			complete: (res) => {
				hideLoading();
			},
		});
	});
}
/**
 * 上传图片
 * @param {Object} ossConfig oss签名配置
 */
export function uploadImg(ossConfig, sourceType) {
	console.log("ossConfig", ossConfig, sourceType)
	// ossConfig.dir = "lsjzg/";
	let tempSourceType = sourceType ? sourceType : ['album', 'camera'];

	return new Promise((resolve, reject) => {

		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			// sourceType: tempSourceType,
			success: (chooseImageRes) => {
				// uploadImg().then(res => {
				// 	console.log('获取文件上传签名==>', res);
				// 	resolve(res);
				// });
				const store = useStore();
				
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const tempFiles = chooseImageRes.tempFiles;

				console.log('tempFiles==>', tempFiles);
				let maxSize = 1024 * 1024 * 5;
			
		
				if (tempFiles[0].size > maxSize) {
					// 无法上传大于10M的图片
					showModal({
						content: '无法上传大于5M的图片'
					});
					return;
				};

				showLoading("上传中");

				console.log('开始上传');
				console.log("tempFilePaths[0]", tempFilePaths[0])
				uni.getImageInfo({
					src: tempFilePaths[0],
					success: res => {
						let canvasWidth = res.width; //图片原始长宽
						let canvasHeight = res.height;
						let base = canvasWidth / canvasHeight;
						if (canvasWidth > 400) {
							canvasWidth = 400;
							canvasHeight = Math.floor(canvasWidth / base);
						}
						let img = new Image();
						img.src = tempFilePaths[0]; // 要压缩的图片
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d');
						canvas.width = canvasWidth;
						canvas.height = canvasHeight;

						//  将图片画到canvas上面   使用Canvas压缩
						ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
						let imgSrc = canvas.toDataURL('image/png');

						uni.uploadFile({
							url: 'https://pos.bestyxb.com/agent-api/aliyun/uploadImage', //附件上传的服务器接口地址，非真实的接口地址
							filePath: imgSrc, //要上传文件资源的路径,不同的组件
							name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容,即附件信息的接收字段名称
							formData: { //HTTP 请求中其他额外的 form data	
								'user': 'test'
							},
							success: (res) => { //回调方法
								if (res.data) {
									let reJson = JSON.parse(res.data);
									if (reJson && reJson.data && reJson.data
										.length > 0) {
										resolve(reJson.data[0].url);

									}
								}
							},
							fail: (res) => {
								console.log('res: ', res);
								uni.showModal({
									title: "提示",
									content: "上传失败，请检查网络" +
										JSON.stringify(res),
									success: function(res) {
										if (res.confirm) {
											console.log(
												"用户点击确定");
											uploadImg();
										} else if (res.cancel) {
											console.log(
												"用户点击取消");
										}
									},
								});
							},
							complete: (res) => {
								hideLoading();
							},
						});
					}
				});

			},
			fail: (res) => {
				console.log('选择图片报错', res)
			}
		});
	});
}

/**
 * 上传图片--签名
 * @param {Object} ossConfig oss签名配置
 */
export function uploadSignImg(ossConfig, tempFilePaths) {
	return new Promise((resolve, reject) => {
	
		console.log("签字 tempFilePaths=" + tempFilePaths)
		uni.getImageInfo({
			src: tempFilePaths,
			success: res => {
				let canvasWidth = res.width; //图片原始长宽
				let canvasHeight = res.height;
				let base = canvasWidth / canvasHeight;
				if (canvasWidth > 400) {
					canvasWidth = 400;
					canvasHeight = Math.floor(canvasWidth / base);
				}
				let img = new Image();
				img.src = tempFilePaths; // 要压缩的图片
				let canvas = document.createElement('canvas');
				let ctx = canvas.getContext('2d');
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;

				//  将图片画到canvas上面   使用Canvas压缩
				ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
				let imgSrc = canvas.toDataURL('image/png');

				uni.uploadFile({
					url: 'https://pos.bestyxb.com/agent-api/merchant/api/ocrs/imgUpload', //附件上传的服务器接口地址，非真实的接口地址
					filePath: imgSrc, //要上传文件资源的路径,不同的组件
					name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容,即附件信息的接收字段名称
					formData: { //HTTP 请求中其他额外的 form data	
						'user': 'test'
					},
					success: (res) => { //回调方法
						if (res.data) {
							let reJson = JSON.parse(res.data);
							if (reJson && reJson.data && reJson.data
								.length > 0) {
								resolve(reJson.data[0].url);

							}
						}
					},
					fail: (res) => {
						console.log('res: ', res);
						uni.showModal({
							title: "提示",
							content: "上传失败，请检查网络" +
								JSON.stringify(res),
							success: function(res) {
								if (res.confirm) {
									console.log(
										"用户点击确定");
									uploadImg();
								} else if (res.cancel) {
									console.log(
										"用户点击取消");
								}
							},
						});
					},
					complete: (res) => {
						hideLoading();
					},
				});
			}
		});
	});
}